package net.pantolomin.nayo.test.perf;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * The transmitted message
 */
public class Message {
	private int id;

	/** The time stamps */
	private long[] timestamps;

	/**
	 * Create a new message
	 * 
	 * @param id
	 *          the id.
	 */
	public Message(int id) {
		this.id = id;
		this.timestamps = new long[] { System.currentTimeMillis() };
	}

	/**
	 * Regen a message
	 * 
	 * @param buffer
	 *          the buffer
	 */
	public Message(ByteBuffer buffer) {
		List<Long> tmp = new ArrayList<Long>(buffer.remaining() / 8);
		if (buffer.remaining() >= 4) {
			this.id = buffer.getInt();
		}
		while (buffer.remaining() >= 8) {
			long l = buffer.getLong();
			if (l > 0L) {
				tmp.add(Long.valueOf(l));
			} else {
				this.timestamps = new long[tmp.size() + 1];
				int i = 0;
				for (Long l2 : tmp) {
					this.timestamps[i++] = l2.longValue();
				}
				this.timestamps[i] = System.currentTimeMillis();
				return;
			}
		}
		this.timestamps = new long[0];
	}

	public int getId() {
		return id;
	}

	/**
	 * Write a message
	 * 
	 * @param buffer
	 *          the buffer
	 */
	public void writeMessage(ByteBuffer buffer) {
		buffer.putInt(this.id);
		for (int i = 0; i < this.timestamps.length; i++) {
			buffer.putLong(this.timestamps[i]);
		}
		buffer.putLong(0L);
	}

	public int getLength() {
		return this.timestamps.length;
	}

	public long[] getTimestamps() {
		return timestamps;
	}
}